import * as RadixRadio from "@radix-ui/react-radio-group";
import { clsxm } from "../helpers";
import { createContext, PropsWithChildren, useContext, useId } from "react";

type RadioGroupContextOption = {
  handleChange: (value: any) => void;
  type: "radio" | "button";
  currentValue: any;
};
const RadioGroupContext = createContext({} as RadioGroupContextOption);

type RadioGroupProps<T> = PropsWithChildren<{
  value: T;
  onChange: (value: T) => void;
  mode?: "vertical" | "horizontal";
  type?: "radio" | "button";
}>;
export function RadioGroup<T>(props: RadioGroupProps<T>) {
  const {
    value,
    children,
    onChange,
    mode = "horizontal",
    type = "radio",
  } = props;
  return (
    <RadioGroupContext.Provider
      value={{ handleChange: onChange, type, currentValue: value }}
    >
      <RadixRadio.Root
        className={clsxm(
          "flex",
          mode === "vertical" && "flex-col",
          mode === "horizontal" && "flex-row",
        )}
      >
        {children}
      </RadixRadio.Root>
    </RadioGroupContext.Provider>
  );
}

type RadioItemProps = PropsWithChildren<{
  value: string | number | boolean;
  className?: string;
}>;

export function RadioItem(props: RadioItemProps) {
  const { value, children, className } = props;
  const { handleChange, type, currentValue } = useContext(RadioGroupContext);
  const id = useId();

  const checked = currentValue === value;

  return (
    <div
      className={clsxm(
        "flex cursor-pointer items-center [&:not(:first-child)]:ml-2",
        className,
      )}
    >
      {type === "radio" && (
        <RadixRadio.Item
          id={id}
          value={value.toString()}
          checked={checked}
          className="relative h-4 w-4 flex-none rounded-full border border-blue-500"
          onClick={() => handleChange(value)}
        >
          <RadixRadio.Indicator
            forceMount
            className={clsxm(
              "absolute left-1/2 top-1/2 h-0 w-0 -translate-x-1/2 -translate-y-1/2 rounded-full bg-blue-500 opacity-0 transition-all duration-150",
              checked && "h-2.5 w-2.5 opacity-100",
            )}
          />
        </RadixRadio.Item>
      )}
      <label htmlFor={id} className="ml-1 cursor-pointer">
        {children}
      </label>
    </div>
  );
}

const a = { a: { b: { c: "ddd" } } };

const path = "a.b.c";

path.split(".").reduce<Record<string, any>>((v, key) => v[key], a);
